<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\Account;
use think\Request;
use think\Validate;
use think\Session;
use think\Db;
class LoginController extends Controller
{
    public function index()
    {
        return view();
    }
    // 登录验证
    public function login(){
        Request::instance()->isPost() || die('request not  post!');
        
        //获取参数
        $param = Request::instance()->param();

        $where['account'] = $param['username'];
        $where['password'] = md5($param['passwd']);
        $where['status'] = 1;
        //数据验证
        $validate = new Validate([
            'username|账号'  =>'require',
            'passwd|密码'  =>'require',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

        $user  = Account::get($where);
        if ($user) {
            Session::set('uid',$user->id,'think');
            Session::set('account',$user->account,'think');
            Session::set('name',$user->true_name,'think');
            Session::set('role_id',$user->role_id,'think');
            //更新登陆时间,IP
            $data = [
                'last_login_time'   => time(),
                'login_ip'          => $_SERVER['REMOTE_ADDR']
            ];
            Db::name('account')->where('id', $user['id'])->update($data);

            $this->redirect('Index/index');
        } else {
            $this->error('账号或者密码错误');
        }
    }

    //注销
    public function quit(){
        Session::delete('uid','think');
        Session::delete('account','think');
        $this->redirect('Login/index');
    }
}